package com.qut.graduate.busrtquery.ui.common;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.text.TextUtils;

import com.qut.graduate.busrtquery.BRTQConstant;
import com.qut.graduate.busrtquery.R;
import com.qut.graduate.busrtquery.utils.common.LogUtils;
import com.qut.graduate.busrtquery.utils.common.PermissionUtils;
import com.qut.graduate.busrtquery.utils.photoselect.PictureSelectUtils;
import com.qut.graduate.busrtquery.utils.uiabout.ToastColorfulUtils;
import com.qut.graduate.busrtquery.view.PictureSelectDialog;

/**
 * 图片选择页面
 */
public class PictureSelectActivity extends Activity {

    // 是否弹吐司，为了保证for循环只弹一次
    private boolean isToast = true;
    private int mCropWidth;
    private int mCropHeight;
    private int mRatioWidth;
    private int mRatioHeight;
    private boolean mCropEnabled;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_picture_select);

        mCropEnabled = getIntent().getBooleanExtra(BRTQConstant.ENABLE_CROP, true);
        mCropWidth = getIntent().getIntExtra(BRTQConstant.CROP_WIDTH, 200);
        mCropHeight = getIntent().getIntExtra(BRTQConstant.CROP_HEIGHT, 200);
        mRatioWidth = getIntent().getIntExtra(BRTQConstant.RATIO_WIDTH, 1);
        mRatioHeight = getIntent().getIntExtra(BRTQConstant.RATIO_HEIGHT, 1);

        String[] permissions = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.CAMERA};
        // 请求应用需要的所有权限
        boolean checkPermissionFirst = PermissionUtils.checkPermissionFirst(this,
                BRTQConstant.PERMISSION_CODE_FIRST, permissions);

        if (checkPermissionFirst) {
            selectPicture();
        }
    }

    /**
     * 处理请求权限的响应
     *
     * @param requestCode 请求码
     * @param permissions 权限数组
     * @param grantResults 请求权限结果数组
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        boolean isPermissions = true;
        for (int i = 0; i < permissions.length; i++) {
            if (grantResults[i] == PackageManager.PERMISSION_DENIED) {
                isPermissions = false;
                if (!ActivityCompat.shouldShowRequestPermissionRationale(this, permissions[i])) {
                    // 用户选择了"不再询问"
                    if (isToast) {
                        ToastColorfulUtils.info("请手动打开该应用需要的权限");
                        isToast = false;
                    }
                }
            }
        }
        isToast = true;
        if (isPermissions) {
            LogUtils.d("----选择图片界面  onRequestPermissionsResult: 允许所有权限", this.getClass());
            selectPicture();
        } else {
            LogUtils.d("----选择图片界面  onRequestPermissionsResult: 有权限不允许", this.getClass());
            finish();
        }
    }

    /**
     * 选择图片
     */
    public void selectPicture() {
        PictureSelectDialog mSelectPictureDialog = new PictureSelectDialog(this,
                R.style.ActionSheetDialogStyle);
        mSelectPictureDialog.setOnItemClickListener(new PictureSelectDialog.OnItemClickListener() {
            @Override
            public void onItemClick(int type) {
                if (type == BRTQConstant.CAMERA) {
                    PictureSelectUtils.getByCamera(PictureSelectActivity.this);
                } else if (type == BRTQConstant.ALBUM) {
                    PictureSelectUtils.getByAlbum(PictureSelectActivity.this);
                } else if (type == BRTQConstant.CANCEL) {
                    finish();
                    // activity延迟150毫秒退出，为了执行完Dialog退出的动画
                    PictureSelectActivity.this.overridePendingTransition(0, R.anim.activity_out);
                }
            }
        });
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // 选择图片中途按返回键
        if (resultCode == RESULT_CANCELED) {
            if (requestCode == BRTQConstant.GET_BY_ALBUM || requestCode == BRTQConstant.GET_BY_CAMERA ||
                    requestCode == BRTQConstant.CROP) {
                finish();
            }
        }
        String picturePath = PictureSelectUtils.getInstance().onActivityResult(this, requestCode, resultCode, data,
                mCropEnabled, mCropWidth, mCropHeight, mRatioWidth, mRatioHeight);
        if (!TextUtils.isEmpty(picturePath)) {
            LogUtils.d("----选择图片界面  选择或拍照的图片地址：" + picturePath, this.getClass());
            Intent intent = new Intent();
            intent.putExtra(BRTQConstant.PICTURE_PATH, picturePath);
            setResult(RESULT_OK, intent);
            finish();
        }
    }

}
